# -*- coding: utf-8 -*-
import json
from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk

ES_HOST = '116.63.42.73'  # es ip
ES_USER = ''  # es 账号
ES_PASSWD = ''  # es 密码
ES_PORT = 9200  # es 端口


class ES():
    def __init__(self):
        self.es = Elasticsearch([ES_HOST], http_auth=(ES_USER, ES_PASSWD), port=ES_PORT, timeout=300)

    def create_index(self, index):
        mappings = {
            "settings": {
                "number_of_shards": 3,  # 数据自动会分成3片存放在不同的节点，提高数据检索速度
                "number_of_replicas": 0
                # 创建0个副本集，如果ES是集群，设置多副本会自动将副本创建到多个节点；设置多副本可以增加数据库的安全性，但是插数据的时候，会先向主节点插入数据，之后再向其余副本同步，会降低插入数据速度，差不多会降低1.4到1.6倍
            },
            "mappings": {
                "book": {  # 索引名
                    "dynamic": True,  # 开启自动添加字段
                    "numeric_detection": True,  # 数字自动检测,当执行索引操作时，如果符合float型，就会自动创建为float
                    "properties": {
                        "author": {"type": "text", "boost": 2},
                        "characters": {"type": "text"},
                        "copies": {"type": "long", "ignore_malformed": False},
                        "otitle": {"type": "text"},
                        "tags": {"type": "text"},
                        "title": {"type": "text"},
                        "year": {"type": "long", "ignore_malformed": False, "index": True},
                        "available": {"type": "boolean"}
                    }
                }
            }
        }
        rtn = self.es.indices.create(index=index, body=mappings, ignore=400)
        print(rtn)


if __name__ == '__main__':
    es = ES()
    index = 'test_01'
    es.create_index(index)
